package com.baidu.disconf.client.watch;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.disconf.client.config.ConfigMgr;
import com.baidu.disconf.client.config.DisClientConfig;
import com.baidu.disconf.client.config.DisClientSysConfig;
import com.baidu.disconf.client.fetcher.FetcherMgr;
import com.baidu.disconf.client.watch.impl.WatchMgrImpl;
import com.baidu.disconf.core.common.path.DisconfWebPathMgr;

/**
 * 鐩戞帶鍣� 瀹炰緥 宸ュ巶
 *
 * @author liaoqiqi
 * @version 2014-7-29
 */
public class WatchFactory {

	protected static final Logger LOGGER = LoggerFactory.getLogger(WatchFactory.class);

	private static final Object hostsSync = new Object();

	protected static ConcurrentHashMap<ClassLoader,WatchMgr> WATCHS = new ConcurrentHashMap<>();

	public static void release(){
		WATCHS.remove(Thread.currentThread().getContextClassLoader());
	}


	/**
	 * @throws Exception
	 */
	public static WatchMgr getWatchMgr(FetcherMgr fetcherMgr) throws Exception {

		if (!ConfigMgr.isInit()) {
			throw new Exception("ConfigMgr should be init before WatchFactory.getWatchMgr");
		}
		synchronized(hostsSync) {
			// 鑾峰彇 Zoo Hosts
			try {
				ClassLoader key = Thread.currentThread().getContextClassLoader();
				if(WATCHS.containsKey(key)){
					return WATCHS.get(key);
				}else{
					String hosts = fetcherMgr.getValueFromServer(DisconfWebPathMgr.getZooHostsUrl(DisClientSysConfig
							.getInstance()
							.CONF_SERVER_ZOO_ACTION));

					String zooPrefix = fetcherMgr.getValueFromServer(DisconfWebPathMgr.getZooPrefixUrl(DisClientSysConfig
							.getInstance
							()
							.CONF_SERVER_ZOO_ACTION));

					WatchMgr watchMgr = new WatchMgrImpl();
					watchMgr.init(hosts, zooPrefix, DisClientConfig.getInstance().DEBUG);
					WATCHS.put(key, watchMgr);
					return watchMgr;
				}
			} catch (Exception e) {
				LOGGER.error("cannot get watch module", e);

			}
		}
		return null;
	}
}
